package DBLayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import ModelLayer.Opening;

public class DBOpening implements IFDBOpening
{
	private Connection con;
	
	public DBOpening()
	{
		con = DBConnection.getInstance().getDBcon();
	}
	
	public Opening getOpeningByDay(String day)
	{
		return singleWhere("DayOfWeek = '" + day + "'");
	}
	
	private Opening singleWhere(String wClause)
	{
		Opening open = new Opening();
		
		ResultSet result = null;
		
		try
		{
			String query = buildQuery(wClause);
			
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			result = stmt.executeQuery(query);
			
			if(result.next())
			{
				open = buildOpening(result);
			}
			
			stmt.close();
		}
		catch(SQLException sqlEx)
		{
			
		}
		
		return open;
	}
	
	private Opening buildOpening(ResultSet result)
	{
		Opening open = new Opening();
		
		try
		{
			open.setId(result.getInt("ID"));
			open.setDayOfWeek(result.getString("DayOfWeek"));
			open.setOpenTime(result.getTime("OpenTime"));
			open.setCloseTime(result.getTime("CloseTime"));
		}
		catch(SQLException sqlEx)
		{
			
		}
		
		return open;
	}
	
	private String buildQuery(String wClause)
	{
		String query = "SELECT ID, DayOfWeek, OpenTime, CloseTime FROM Opening";
		
		if(wClause.length() > 0)
		{
			query += " WHERE " + wClause;
		}
		
		return query;
	}
}
